const fs = require('fs');
const path = require('path');
const web3 = require('./web3');

module.exports = exports = {};

function load_keyfiles(datadir, keystore='keystore') {
  if (!datadir || !fs.existsSync(datadir)) {
    throw `datadir not found: ${datadir}`;
  }
  const keystore_path = path.join(datadir, keystore);
  if (!fs.statSync(keystore_path).isDirectory()) {
    throw `keystore dir not found: ${keystore_path}`;
  }

  return fs.readdirSync(keystore_path).map((file) => {
    const f = fs.readFileSync(path.join(keystore_path, file), 'utf8');
    let j = null;
    try {
      return JSON.parse(f);
    } catch (e) {
      console.warn('WARN: ignoring wrong format keystore file: ', f);
    }

    return null;
  }).filter((val) => {
    return val !== null;
  });
};
exports.load_keyfiles = load_keyfiles;


exports.before_parse = function before(program) {
  const comm = program.command('eth');
  comm.command('list')
    .description('list ethereum keyfiles')
    .action(() => {
      let keyfiles = load_keyfiles(program.opts().datadir);
      if (!keyfiles || !keyfiles.length) {
        console.log('no available keyfiles yet!');
      } else {
        console.log('keyfiles:');
        for (const i in keyfiles) {
          console.log(i, ':', keyfiles[i].address);
        }
      }
    });;

  comm.command('balance <ethacc>')
    .description('get balance from etherum account')
  /*
    .option('--ethacc <ethacc>',
            'ethereum account, or $ZETHER_ETHACC',
            process.env.ZETHER_ETHACC)
    .option('--ethpass <ethpass>',
            'ethereum account, or $ZETHER_ETHPASS',
            process.env.ZETHER_ETHPASS)
  */
    .action((ethacc) => {
      if (!ethacc) {
        throw 'ethereum account not set!';
      }

      web3.eth.getBalance(ethacc)
        .then((bal) => {
          console.log(`account: ${ethacc}\nbalance: ${bal} wei`);
        }, (err) => {
          console.error('error: ', err);
        });
      
      /*
        let keyfiles = load_keyfiles(program.opts().datadir);
        let keyfile = null;
        for (const i in keyfiles) {
        if (keyfiles[i].address.startsWith(options.ethacc)) {
        keyfile = keyfiles[i];
        break;
        }
        }

        if (!keyfile) {
        throw `ethacc not available: ${options.ethacc}`;
        }
      */
      
    });

  comm.command('transfer <sender> <receiver> <balance>')
    .option('--ethpass <ethpass>', 'password of the sender', '')
    .action(async (sender, receiver, balance, options) => {
      let nonce = await web3.eth.getTransactionCount(sender);

      const ethpass = options.ethpass ? options.ethpass : '';
      // await web3.eth.personal.unlockAccount(sender, ethpass, 10);

      const receipt = await web3.eth.sendTransaction({
        from: sender,
        to: receiver,
        gas: '21000',
        gasPrice: '1000000000',
        nonce,
        value: balance,
      });
      
      console.log('receipt: ', receipt);
    });

};

exports.after_parse = function after(program) {
};
